#include <2025Linux.h>
int main(int argc, char *argv[])
{
    // ./07_azhen 192.168.72.128 12345
    ARGS_CHECK(argc,3);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET; // ipv4
    addr.sin_port =  htons(atoi(argv[2])); // "12345" --> 小端 12345 --> 大端 12345
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(sockfd,-1,"socket");
    int flag = 1; // 定义一个int的flag，值为1说明要无视
    int ret = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(flag));
    ERROR_CHECK(ret,-1,"setsockopt");
    ret = bind(sockfd,(struct sockaddr *)&addr, sizeof(addr));
    ERROR_CHECK(ret,-1,"bind");
    ret = listen(sockfd,10);
    ERROR_CHECK(ret,-1,"listen");

    // 因为每次select时，监听集合可能不一样，所以我们把监听和就绪分离了
    fd_set monitorset; //监听集合
    fd_set readyset; //就绪集合 
    FD_ZERO(&monitorset);
    FD_SET(sockfd,&monitorset);
    char buf[4096] = {0};
    int netfd = -1; // -1 说明阿强死了
    while(1){
        memcpy(&readyset,&monitorset,sizeof(fd_set));//用monitorset覆盖readyset
        select(1024,&readyset,NULL,NULL,NULL);//为什么不写monitorset--->我们希望monitorset不会被select改变
        if(FD_ISSET(sockfd,&readyset)){ // 阿强连上了
            netfd = accept(sockfd,NULL,NULL);
            printf("aqiang is connected!\n");
            FD_CLR(sockfd,&monitorset);
            FD_SET(STDIN_FILENO,&monitorset);
            FD_SET(netfd,&monitorset);
        }
        if(netfd != -1 && FD_ISSET(STDIN_FILENO,&readyset)){ // 阿强活着 && 阿珍输入了内容
            memset(buf,0,sizeof(buf));
            read(STDIN_FILENO,buf,sizeof(buf));
            write(netfd,buf,strlen(buf));
        }
        if(netfd != -1 && FD_ISSET(netfd,&readyset)){ // 阿强活着 && 阿强来消息了
            memset(buf,0,sizeof(buf));
            ssize_t sret = recv(netfd,buf,sizeof(buf),0);
            if(sret == 0){ // 阿强死了
                FD_CLR(STDIN_FILENO,&monitorset);
                FD_CLR(netfd,&monitorset);
                FD_SET(sockfd,&monitorset);
                close(netfd);
                netfd = -1;
                printf("wohuihaohaode\n");
                continue;
            }
            printf("buf = %s\n", buf);
        }
    }
    return 0;
}

